package models

import (
	"errors"
	"fmt"
	"qysoft/libs/params"
	"reflect"
	"strings"
	"time"

	//	"github.com/astaxie/beego"

	"github.com/astaxie/beego/orm"
)

type Role struct {
	Id       string      `orm:"column(id);pk"`
	Name     string      `orm:"column(name);null"`
	Type     int         `orm:"column(type)"`
	Remark   string      `orm:"column(remark);null"`
	Status   int         `orm:"column(status)"`
	Isdelete int         `orm:"column(isdelete)"`
	Ctime    time.Time   `orm:"column(ctime);type(timestamp with time zone)"`
	Creater  string      `orm:"column(creater)"`
	Utime    time.Time   `orm:"column(utime);type(timestamp with time zone)"`
	Updater  string      `orm:"column(updater)"`
	Resource []*Resource `orm:"rel(m2m)"`
	User     []*User     `orm:"reverse(many)"`
	// State    []*State    `orm:"reverse(many)"`
	//	Stateinstance []*Stateinstance `orm:"reverse(many)"`
}

func (t *Role) TableName() string {
	return "sys_role"
}

func init() {
	orm.RegisterModel(new(Role))
}

// AddRole insert a new Role into database and returns
// last inserted Id on success.
func AddRole(m *Role) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetRoleById retrieves Role by Id. Returns error if
// Id doesn't exist
func GetRoleById(id string) (v *Role, err error) {
	o := orm.NewOrm()
	v = &Role{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// GetAllRole retrieves all Role matches certain condition. Returns empty list if
// no records exist
func GetAllRole(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Role))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	qs = qs.Filter("Isdelete", 0)
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []Role
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				s := make(map[string]interface{})
				ve := reflect.ValueOf(v)
				t := reflect.TypeOf(v)
				for i := 0; i < t.NumField(); i++ {
					//					beego.Debug(t.Field(i).Name, ve.Field(i).Interface())
					s[t.Field(i).Name] = ve.Field(i).Interface()
				}
				s["Tname"] = params.GetRoleType(v.Type)
				s["Sname"] = params.GetStatus(v.Status)
				ml = append(ml, s)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// UpdateRole updates Role by Id and returns error if
// the record to be updated doesn't exist
func UpdateRoleById(m *Role) (err error) {
	o := orm.NewOrm()
	v := Role{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteRole deletes Role by Id and returns error if
// the record to be deleted doesn't exist
func DeleteRole(id string) (err error) {
	o := orm.NewOrm()
	v := Role{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&Role{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

//Desc 软删除角色数据
//Param id int64
//Param uname string
//return error
func SoftDeleteRole(id string, uname string) (err error) {
	o := orm.NewOrm()
	v := Role{Id: id}
	if err = o.Read(&v); err == nil {
		v.Isdelete = 1
		v.Updater = uname
		v.Utime = time.Now()
		_, err = o.Update(&v)
	}
	return
}

//根据userid检查该用户权限，返回资源列表和错误
func AccessList(uid string) (list []orm.Params, err error) {
	user, err := GetUserById(uid)
	//	role, err := GetRoleByUserId(uid)
	if err != nil {
		return nil, err
	}

	resources, _ := GetResourceByRoleId(user.Role[0].Id, 0)

	for _, n := range resources {
		list = append(list, n)
	}

	return list, nil
}

func UpdateUserRole(roleId string, userId string) (int64, error) {
	o := orm.NewOrm()
	role := Role{Id: roleId}
	user := User{Id: userId}
	m2m := o.QueryM2M(&user, "Role")
	num, err := m2m.Add(&role)
	// m2m.
	return num, err
}
func DelRoleById(Id string) (int64, error) {
	o := orm.NewOrm()
	status, err := o.Delete(&Role{Id: Id})
	return status, err
}

func GetAllRoleList() (roles []orm.Params, count int64) {
	o := orm.NewOrm()
	role := new(Role)
	qs := o.QueryTable(role)
	count, err := qs.Values(&roles)
	if err != nil {
		fmt.Println(err)
	}
	return roles, count
}

//func AddRoleResource(roleId int64, resourceId int64) error {
//	o := orm.NewOrm()
//	var rr RoleResource
//	rr.RoleId = roleId
//	rr.ResourceId = resourceId
//	_, err := o.Insert(&rr)
//	//	m2m := o.QueryM2M(&resource, "Role")
//	//	num, err := m2m.Add(&role)
//	return err
//}

func GetRoleByName(Name string) (err error, role Role) {
	o := orm.NewOrm()
	role = Role{Name: Name}
	err = o.Read(&role, "Name")
	return err, role
}
func DelUserRole(roleId int64) error {
	o := orm.NewOrm()
	_, err := o.QueryTable("sys_user_sys_roles").Filter("sys_role_id", roleId).Delete()
	return err
}

func DelUserRoleByUserId(userId string) error {
	o := orm.NewOrm()
	sql := "DELETE FROM public.sys_user_sys_roles ta WHERE ta.sys_user_id = ?"
	_, err := o.Raw(sql, userId).Exec()
	return err
}
func AddUserRole(roleId, userId string) (int64, error) {
	o := orm.NewOrm()
	role := Role{Id: roleId}
	user := User{Id: userId}
	m2m := o.QueryM2M(&user, "Role")
	num, err := m2m.Add(&role)
	return num, err
}

//Desc 获取所有角色
//return []Role,error
func GetAllOrleList() ([]Role, error) {
	var roleList []Role
	sql := "SELECT * FROM public.sys_role ta WHERE ta.isdelete=0"
	o := orm.NewOrm()
	_, err := o.Raw(sql).QueryRows(&roleList)
	return roleList, err
}

// 获取单位管理员角色列表，排除系统管理员
//Desc 获取所有角色
//return []Role,error
func GetOrgRoleList(user *User) (rolelist []Role, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Role)).Filter("isdelete", 0).Filter("status", 1).Filter("Type__gte", user.Role[0].Type)
	_, err = qs.All(&rolelist)
	return
}

//// 软删除RoleResource by Id and returns error if
//// the record to be deleted doesn't exist
//func SoftDeleteRoleResource(id int64) (err error) {
//	o := orm.NewOrm()
//	v := RoleResource{Id: id}
//	// ascertain id exists in the database
//	if err = o.Read(&v); err == nil {
//		v.Isdelete = 1
//		_, err = o.Update(&v)
//	}
//	return
//}

func DeleteRoleResourceByRoleId(roleId string) (err error) {
	o := orm.NewOrm()
	_, err = o.Raw("DELETE FROM sys_role_sys_resources WHERE sys_role_id=?", roleId).Exec()
	return
}

// 软删除RoleResource by roleId and returns error if
// the record to be deleted doesn't exist
func SoftDeleteRoleResourceByRoleId(roleId string) (err error) {
	o := orm.NewOrm()
	_, err = o.Raw("update sys_role_sys_resources set isdelete=1,utime=? WHERE sys_role_id=?", time.Now(), roleId).Exec()
	return
}

// 判断角色对某资源是否有权限，角色id，资源id，返回bool
func GetRoleOwnerResource(roleid, resID string) bool {
	var rrs []orm.Params
	o := orm.NewOrm()
	qs := o.QueryTable(new(Role)).Filter("Id", roleid).Filter("Resource__SysResource__Id", resID).Limit(-1)
	num, err := qs.Values(&rrs)
	if err == nil && num > 0 {
		return true
	} else {
		return false
	}
}

//// 软删除用户角色关系，根据Id ，返回error
//// the record to be deleted doesn't exist
//func SoftDeleteUserRole(id int64) (err error) {
//	o := orm.NewOrm()
//	v := UserRole{Id: id}
//	// ascertain id exists in the database
//	if err = o.Read(&v); err == nil {
//		v.Isdelete = 1
//		_, err = o.Update(&v)
//	}
//	return
//}

//Desc 根据用户删除用户角色关系
//Param userId 用户id
//return error
func DeleteUserRoleByUserId(userId string) error {
	o := orm.NewOrm()
	sql := "DELETE FROM public.sys_user_sys_roles ta WHERE ta.sys_user_id = ?"
	_, err := o.Raw(sql, userId).Exec()
	return err
}
